package com.jerry.project;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;


public class SearchEventServlet extends HttpServlet {
	@Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
		JSONObject jsonobj=null;
		String keyword=null;
		String tag=null;
		String sort_by=null;
		String user=null;
		String fuckstring="\0";
		try {
			jsonobj=new JSONObject(reqToJSONString.reqToJSONString(req));
			if(jsonobj.has("keyword")){
				keyword=jsonobj.getString("keyword");
			}
			if(jsonobj.has("sort_by")){
				sort_by=jsonobj.getString("sort_by");
			}
			if(jsonobj.has("tag")){
				tag=jsonobj.getString("tag");
			}
			if(jsonobj.has("user")){
				user=jsonobj.getString("user");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
        Key eventKey = KeyFactory.createKey("EventKind", "event");
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        //req need id
        /*Filter nameFilter =FilterOperator.EQUAL.of("name",keyword);
        Filter tagFilter =FilterOperator.EQUAL.of("tag", keyword);
        Filter queryFilter = CompositeFilterOperator.or(nameFilter, tagFilter);
        Query query = new Query("Event", eventKey).setFilter(queryFilter);*/
        Query query;
        List<Entity> result=new ArrayList<Entity>();
        
        if(tag!=null&&tag!=fuckstring){
        	Filter queryFilter =FilterOperator.EQUAL.of("tag", tag);
        	query = new Query("Event", eventKey).setFilter(queryFilter);
        }
        else{
        	query = new Query("Event", eventKey);
        }
        if(keyword!=null&&keyword!=fuckstring){
    		List<Entity> events = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(100));
        	for(Entity e:events){
        		if(e.getProperty("name").toString().toLowerCase().split(keyword.toLowerCase()).length!=0){
        			if(e.getProperty("name").toString().toLowerCase().split(keyword.toLowerCase())[0].length()==e.getProperty("name").toString().toLowerCase().length()){
        			/*if(e.getProperty("tag").toString().toLowerCase().split(keyword.toLowerCase()).length!=0){
        				if(e.getProperty("tag").toString().toLowerCase().split(keyword.toLowerCase())[0].length()==e.getProperty("tag").toString().toLowerCase().length()){
        			
        				}
        				else result.add(e);
        			}
        			else result.add(e);*/
        				
        			}
        			else result.add(e);
        		}
        		else result.add(e);
        	}
    	}
    	else{
    		result = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(100));
    	}
    	if(user!=null&&user!=fuckstring){
    		for(Entity event:result){
    			event.setProperty("userlikeit", 0);
    		}
			Key accountKey = KeyFactory.createKey("AccountKind", "account");
			Filter userFilter =FilterOperator.EQUAL.of("account", user);
			Query interestquery = new Query("Account", accountKey).setFilter(userFilter);
			List<Entity> interest = datastore.prepare(interestquery).asList(FetchOptions.Builder.withLimit(100));
			for(Entity userlike:interest){
				for(Entity event:result){
					if(userlike.getProperty("interestedEventID").toString().equals(event.getProperty("id").toString())){
						event.setProperty("userlikeit", 1);
					}
				}
			}
		}
    	if(sort_by!=null&&sort_by!=fuckstring){
    		Sort.sortbyWhat(result, sort_by,1);
    	}
    	if(ToJSON.ListToJSON(result,"events")!=null){
    		resp.getWriter().print(ToJSON.ListToJSON(result,"events"));
    	}
	}
}